<template>
  <div>
    <div class="title">
      <van-nav-bar title="城市列表" left-arrow @click-left="$router.go(-1)" />
    </div>
    <van-index-bar :index-list="indexlist">
      <van-index-anchor :index="item" v-for="item in indextitle" :key="item"
        >{{ item }}
        <van-cell
          :title="val.label"
          v-for="(val, k) in all[item]"
          :key="k"
          @click="fn(val)"
        />
      </van-index-anchor>
    </van-index-bar>
  </div>
</template>

<script>
import { getcity, gethotcity } from '@/api/area'
export default {
  name: 'city-page',
  components: {},
  props: {},
  data() {
    return {
      currentcity: JSON.parse(window.localStorage.getItem('currentcity')) || {
        label: '北京',
        value: 'AREA|88cff55c-aaa4-e2e0',
        pinyin: 'beijing',
        short: 'bj'
      },
      indexlist: [
        '#',
        '热',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ],
      indextitle: [
        '当前城市',
        '热门城市',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ],
      all: {}
    }
  },
  computed: {},
  watch: {},
  async created() {
    const res = await getcity()
    const area = res.body
    const res1 = await gethotcity()
    const hotarea = res1.body
    const all = {}
    this.indexlist.forEach((item) =>
      ['#', '热'].includes(item) ? '' : (all[item] = [])
    )
    area.forEach((item) => {
      all[item.pinyin[0].toUpperCase()].push(item)
    })
    all['当前城市'] = [this.currentcity]
    all['热门城市'] = hotarea
    this.indextitle.forEach((item) =>
      all[item].length ? '' : all[item].push('暂无城市')
    )
    this.all = all
  },
  methods: {
    fn(val) {
      this.all['当前城市'] = [val]
      localStorage.setItem('currentcity', JSON.stringify(val))
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped lang="less">
.title {
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 46px;
  z-index: 100;
}
.van-index-bar {
  margin-top: 47px;
}
/deep/.van-index-anchor--sticky {
  color: #111;
}
/deep/.van-index-bar__index {
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  margin-right: 5px;
  display: inline-block;
  padding: 2px 6px;
  z-index: 3;
}
/deep/.van-index-bar__index--active {
  color: #fff;
  background-color: rgb(33, 185, 122);
  border-radius: 50%;
}
</style>
